package 类加载与字节码技术.类加载器.自定义类加载器;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;


public class MyClassLoadertest2 {
    public static void main(String[] args) throws ClassNotFoundException {
        MyClassLoader2 classLoader = new MyClassLoader2("D:\\IdeaProjects\\JVM\\src\\");
        Class<?> c1 = classLoader.loadClass("helloworld");
        System.out.println(c1.getClassLoader().getClass().getClass());
        System.out.println(c1.getClassLoader().getClass().getName());
        System.out.println(c1.getClassLoader().getParent().getClass());
        System.out.println(c1.getClassLoader().getParent().getClass().getName());

    }
}

class MyClassLoader2 extends ClassLoader {
    private String bytecodepath;

    public MyClassLoader2(String bytecodepath) {
        this.bytecodepath = bytecodepath;
    }


    @Override // name 就是类名称
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        BufferedInputStream bis = null;
        ByteArrayOutputStream baos = null;
        try {
            String path = bytecodepath + name + ".class";
            bis = new BufferedInputStream(new FileInputStream(path));
            baos = new ByteArrayOutputStream();

            int len;
            byte[] bytes = new byte[1024];
            while ((len = bis.read(bytes)) != -1) {
                baos.write(bytes, 0, len);
            }

            byte[] bytes1 = baos.toByteArray();

            Class<?> aClass = defineClass(name, bytes1, 0, bytes1.length);
            return aClass;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }
}

